package data;

import com.mongodb.MongoClient;
import event.EventBase;
import event.EventEnum;
import event.EventSystem;
import helper.Helper;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;

/**
 * flow:
 * 1, any mongoclient connected by UI, will use add() to add this client to map
 * 2, in add(), a event with mongoclient data will dispatched
 */
public class DatabaseClientCollect{
    private static DatabaseClientCollect instance;
    private BidiMap<String, DatabaseClient> databaseClientBidiMap;
    private DatabaseClientCollect() {
        databaseClientBidiMap = new TreeBidiMap();
    }

    public static DatabaseClientCollect instance() {
        if (instance == null) {
            instance = new DatabaseClientCollect();
        }
        return instance;
    }

    public void add(DatabaseClient client) {
        String id = Helper.genUUIDString();
        databaseClientBidiMap.put(id, client);

        EventSystem.instance().dispatch(new EventBase(EventEnum.mongoClientAdd, client));
    }

    public void remove(MongoClient client) {
        if (databaseClientBidiMap.containsValue(client)) {
            databaseClientBidiMap.removeValue(client);
        }
    }
}
